package com.hzo.great.leisuregreat.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.widget.ImageView;
import android.widget.TextView;

import com.hzo.great.leisuregreat.R;


/**
 * Created by Administrator on 2017/4/5.
 */

public class LoadingDialog {

    private static Activity context;
    private static Dialog loadDialog;
    private static AnimationDrawable animationDrawable;

    private LoadingDialog(Activity context) {
        LoadingDialog.context = context;
    }

    public static LoadingDialog getInstance(Activity context) {
        return new LoadingDialog(context);
    }

    public void showLoadDialog(String msg) {
        if (context == null)
            return;
        if (context.isFinishing()) {
            closeLoadDialog();
            return;
        }
        if (loadDialog == null) {
            loadDialog = new Dialog(context);
            loadDialog.setContentView(R.layout.loading_dialog);
            loadDialog.setCancelable(false);
            loadDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            loadDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                }
            });
        }
        TextView notice_msg = loadDialog.findViewById(R.id.tv_loading_text);
        ImageView progress = loadDialog.findViewById(R.id.progressbar1);

        if (animationDrawable == null) {
            animationDrawable = (AnimationDrawable) progress.getBackground();
        }
        notice_msg.setText(msg);
        if (animationDrawable != null) {
            animationDrawable.start();
        }
        try {
            loadDialog.show();
        } catch (Exception e) {
            System.out.println("loading框show方法出错，异常被捕获");
            e.printStackTrace();
        }
    }

    /**
     * 关闭loading框
     */
    public static void closeLoadDialog() {
        if (loadDialog != null) {

            if (animationDrawable != null) {
                animationDrawable.stop();
            }
            animationDrawable = null;

            try {
                loadDialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("之前的activity被销毁，dialog关闭异常。该报错可以忽略");
            }
            loadDialog = null;
        }
    }
}
